<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="searchQuery"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import {
  onBeforeUnmount,
  ref,
  shallowRef,
  defineProps,
  defineEmits,
  watch,
} from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

import { throttle } from "lodash-es";
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const toolbarConfig = {};
const editorConfig = {MENU_CONF: {} , placeholder: "请输入内容..." };
editorConfig.MENU_CONF['uploadImage'] = {
      server: 'https://shalong.taiyanyue.top/api/common/richTextFileUpload', 
 
      timeout: 5 * 1000, // 5s
 
      fieldName: 'file',
      // meta: { token: 'xxx', a: 100 },
      metaWithUrl: true, // 参数拼接到 url 上
      headers: { Accept: 'text/x-json' },
 
      maxFileSize: 10 * 1024 * 1024, // 10M
 
      base64LimitSize: 5 * 1024, // 5kb 以下插入 base64
 
      onBeforeUpload(files) {
        console.log('onBeforeUpload', files)
 
        return files // 返回哪些文件可以上传
        // return false 会阻止上传
      },
      onProgress(progress) {
        console.log('onProgress', progress)
      },
      onSuccess(file, res) {
        console.log('onSuccess', file, res)
      },
      onFailed(file, res) {
        console.log('onFailed', file, res)
      },
      onError(file, err, res) {
        alert(err.message)
        console.error('onError', file, err, res)
      },customInsert(res, insertFn) {
        const p = res.content.data.data.url
    // TS 语法
    // customInsert(res, insertFn) {                  // JS 语法
    // res 即服务端的返回结果

    // 从 res 中找到 url alt href ，然后插入图片
    console.log("============",p)
    insertFn(p, "上传图片", p)
  },
    }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
const emit = defineEmits([
  "update:modelValue", // 用于v-model双向绑定
  "search", // 搜索事件
  "change", // 内容变化事件(带节流)
]);

const props = defineProps({
  // 初始搜索值
  modelValue: {
    type: String,
    default: "",
  },
  // 节流延迟时间(毫秒)
  throttleDelay: {
    type: Number,
    default: 500,
  },
});
// 搜索查询内容
const searchQuery = ref(props.modelValue);

// 创建节流函数
const throttledEmit = throttle((value) => {
  emit("change", value);
}, props.throttleDelay);

// 监听searchQuery变化
watch(searchQuery, (newValue) => {
  // 触发v-model更新
  emit("update:modelValue", newValue);

  // 节流触发change事件
  throttledEmit(newValue);
});
</script>
